﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Data.SqlClient;

namespace vote
{
    public partial class back_addVote : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                addOptions(2);
            }
            else
            {
                addOptions(int.Parse(ddlOpCount.SelectedValue));
            }
        }

        private void addOptions(int num)
        {
            for (int i = 1; i <= num; i++)
			{
                Poll option = new Poll();
                option.OptionIndex = i;
                phOptions.Controls.Add(option);
			}
            
        }

        protected void addVote_Click(object sender, EventArgs e)
        {
            List<string> sqls = new List<string>();
            List<SqlParameter[]> listParams = new List<SqlParameter[]>();

            SqlParameter[] parameters = new SqlParameter[3];
            parameters[0] = new SqlParameter("@title", SqlDbType.VarChar, 70);
            parameters[0].Value = tbTitle.Text;
            parameters[1] = new SqlParameter("@Singlemode", SqlDbType.Bit);
            parameters[1].Value = rblSelectPattern.Items[0].Selected;
            parameters[2] = new SqlParameter("@colmode", SqlDbType.Bit);
            parameters[2].Value = rblPicStyle.Items[0].Selected;

            int voteId = AccessDBUtil.ExecuteInsert("insert into [voteTitle]([title],[singleMode],[colMode]) values(@title,@Singlemode,@colmode)",parameters);
            
            for (int i = 0; i < phOptions.Controls.Count; i++)
            {
                parameters = new SqlParameter[4];
                parameters[0] = new SqlParameter("@parentId", SqlDbType.Int);
                parameters[0].Value = voteId;
                parameters[1] = new SqlParameter("@optionName", SqlDbType.VarChar, 70);
                parameters[1].Value = ((Poll)phOptions.Controls[i]).OptionName;
                parameters[2] = new SqlParameter("@color", SqlDbType.VarChar, 50);
                parameters[2].Value = ((Poll)phOptions.Controls[i]).OptionColor;
                parameters[3] = new SqlParameter("@ballCount", SqlDbType.Int);
                parameters[3].Value = ((Poll)phOptions.Controls[i]).Ballots;

                sqls.Add("insert into [voteOption]([parentId],[option],[color],[ballots]) values(@parentId,@optionName,@color,@ballCount)");
                listParams.Add(parameters);
            }

            AccessDBUtil.ExecuteTrans(sqls, listParams);
        }
}
}